<template>
  <div class="batch-create-container">
    <CreateClient
      v-if="isClientInfo"
      ref="clientInfoRef"
      :is-other-info-disabled="!isOtherInfo"
      :is-client-disabled="!isClientInfo"
    />
    <div class="batch-create-list">
      <el-button
        size="small"
        type="primary"
        class="add-order-tab"
        @click="addTab">添加订单 <i class="el-icon-plus"/> </el-button>
      <div>
        <el-tabs v-model="activePage" :closable="pageList.length > 1" type="border-card" @tab-remove="removeTab">
          <el-tab-pane
            v-for="(item, index) in pageList"
            :key="index"
            :label="`订单${index+1}`"
            :name="index.toString()">
            <!-- <span slot="label">{{ `订单${index+1}` }}</span> -->
            <div class="batch-create-title">
              <span class="title">订单引用</span>
              <el-dropdown trigger="click">
                <div class="dropdown-title" >
                  <span style="flex: 1;">请选择</span><i class="el-icon-arrow-down el-icon--right"/>
                </div>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    v-for="(page, j) in pageList"
                    :key="j"
                    :disabled="Number(activePage) === j"
                    @click.native="quoteOrder(j)"
                  >
                    <div class="dropdown-item">订单{{ j+1 }}</div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
            <div class="batch-create-item">
              <CreateOrder
                :tip="'说明：选择资源后请填写对应的订单信息并保存。没有提交订单信息的选项无法生成订单。'"
                :ref="`orderInfoRef${index}`"
                :is-disabled-without-file="!isOtherInfo"
                :is-file-disabled="!isPublishInfo"
                @orderTypeChange="orderTypeChange($event, index)"
              />
              <CreateResource
                :ref="`resourceInfoRef${index}`"
                :order-info-ref="{
                  $refs: $refs,
                  orderInfoRef: `orderInfoRef${index}`
                }"
                :is-disabled-without-file="!isOtherInfo"
                :is-file-disabled="!isPublishInfo"
                :order-type="orderTypeList[index]"
                style="padding-top:0px;"
              />
              <CreatePublish :ref="`publishInfoRef${index}`" :is-file-disabled="!isPublishInfo" style="margin-bottom:30px;"/>

              <div class="box-block" style="padding: 0 24px;">
                <costBreakdownComponent
                  :ref="`discountInfoRef${index}`"
                  :is-create="true"
                  :is-detail="false"
                  :is-order="true"
                  :cost-belong-type="0"/>
              </div>

              <!-- <DiscountInfo :is-create="true" :ref="`discountInfoRef${index}`" :is-disabled-without-micro="!isCostInfo" :is-disabled-micro="!isOtherInfo" style="padding-bottom: 14px"/> -->

              <div style="margin: 24px 0;padding: 0 24px;position:relative;">
                <Title title="关联合同和发票" font-size="16px" />
                <div style="margin-top: 17px;">
                  <InvoiceAndContract
                    :ref="`ContractSelect${index}`"
                    :sub-title="'关联合同'"
                    :is-disabled="!isOtherInfo"
                    :type="1"
                    :related-contract-style="{
                      position: 'absolute',top: '-7px',right: '24px'
                    }"
                    placeholder="请输入合同编号/合同名称" />
                </div>
                <div style="margin-top: 10px;">
                  <InvoiceAndContract :ref="`InvoiceSelect${index}`" :sub-title="'关联发票'" :is-disabled="!isOtherInfo" :type="2" target-keyword="no" placeholder="请输入发票编号/发票号码" />
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <fixed-pagination>
      <div class="center">
        <el-button v-if="hasRouteAuth('crm:orderList:add')" :loading="btnLoading" type="primary" size="small" @click="toSubmit">批量创建订单</el-button>
        <el-button v-if="hasRouteAuth('crm:orderList:addDraft')" :loading="btnLoading" type="info" size="small" @click="toSubmit(false)">批量保存草稿</el-button>
        <el-button type="info" size="small" @click="toBack">取消</el-button>
      </div>
    </fixed-pagination>
    <Dialog
      ref="publishDialogRef"
      :btn1="'确认创建'"
      :btn2="'取消'"
      :summary="dialogSummary"
      :title="dialogTitle"
      @handelOK="createOrder" />
    <limitTable ref="limitTable" />
  </div>
</template>

<script>
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';
import ElMessage from '@/utils/message';
// api
import { createOrderBatch } from '@/api/order';
// 组件
import CreateClient from '@/components/CreateOrder/createClient';
import CreateOrder from '@/components/CreateOrder/createOrderEx';
import CreateResource from '@/components/CreateOrder/createResource';
import CreatePublish from '@/components/CreateOrder/createPublish';
import costBreakdownComponent from '@/components/CreateOrder/costList';
import limitTable from '../model/limitTable';
import InvoiceAndContract from '@/components/CreateOrder/InvoiceAndContract';
import Title from '@/components/Title';
import Dialog from '@/components/CreateOrder/orderDetail/dialog';
export default {
  components: {
    CreateClient, Dialog, CreateOrder, costBreakdownComponent, CreateResource, CreatePublish,
    InvoiceAndContract, Title, limitTable
  },
  data() {
    return {
      pageList: [1],
      quoteIndex: '',
      paramsData: {},
      activePage: '0',
      btnLoading: false,
      orderTypeList: [],
      dialogSummary: '',
      dialogTitle: '',
      isEdit: false
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    isClientInfo() {
      return hasRouteAuth('crm:orderList:clientInfo');
    },
    isPublishInfo() {
      return this.isDraftEdit || hasRouteAuth('crm:orderList:publishInfo');
    },
    isCostInfo() {
      return this.isDraftEdit || hasRouteAuth('crm:orderList:costInfo');
    },
    isOtherInfo() {
      return this.isDraftEdit || hasRouteAuth('crm:orderList:otherInfo');
    },
    isDraftEdit() {
      // 在新建、编辑草稿状态时，如果拥有“新建草稿”的权限，则所有信息可以编辑
      return !this.isEdit && hasRouteAuth('crm:orderList:addDraft');
    }
  },
  methods: {
    hasRouteAuth,
    addTab() {
      this.pageList.push([1]);
    },
    removeTab(index) {
      const that = this;
      this.$confirm('是否删除这个订单', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'del-message del-message-cancel',
        iconClass: 'del-icon',
        center: true,
        type: 'warning'
      }).then(() => {
        that.pageList.splice(Number(index), 1);
        if (Number(this.activePage) > (that.pageList.length - 1)) {
          this.activePage = that.pageList.length - 1 + '';
        }
      });
    },
    // 引用
    quoteOrder(index) {
      const that = this;
      this.$confirm('确认覆盖当前表单的所有信息？', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'del-message del-message-cancel',
        iconClass: 'del-icon',
        center: true,
        type: 'warning'
      }).then(() => {
        const orderInfoRef = that.$refs[`orderInfoRef${this.activePage}`];
        const discountInfoRef = that.$refs[`discountInfoRef${this.activePage}`];
        const resourceInfoRef = that.$refs[`resourceInfoRef${this.activePage}`];
        const publishInfoRef = that.$refs[`publishInfoRef${this.activePage}`];

        const contractSelectRef = that.$refs[`ContractSelect${this.activePage}`];
        const invoiceSelectRef = that.$refs[`InvoiceSelect${this.activePage}`];
        const params = that.getRefData(index);
        const related = that.getRelatedIds(index);

        this.orderTypeChange(params.orderInfo.orderType, this.activePage);
        if (orderInfoRef && orderInfoRef instanceof Array) orderInfoRef[0].insertDetail(params);
        if (discountInfoRef && discountInfoRef instanceof Array) discountInfoRef[0].insertDetail(params.costBreakdown);
        if (resourceInfoRef && resourceInfoRef instanceof Array) resourceInfoRef[0].insertDetail(params);
        if (publishInfoRef && publishInfoRef instanceof Array) publishInfoRef[0].insertDetail(params);
        if (contractSelectRef && contractSelectRef instanceof Array) contractSelectRef[0].setDefault(related.contract);
        if (invoiceSelectRef && invoiceSelectRef instanceof Array) invoiceSelectRef[0].setDefault(related.invoiceInfo);
      });
    },
    toSubmit(isValidate = true) {
      const data = [];
      const orderOperatorList = [];
      const clientList = [];
      this.pageList.forEach((i, index) => {
        const itemData = this.getRefData(index);
        data.push(itemData);
        if (itemData.orderInfo && itemData.orderInfo.orderOperator) {
          itemData.orderInfo.orderOperator.forEach(j => {
            orderOperatorList.push(j);
          });
        }
        if (itemData.clientInfo) {
          clientList.push({ id: itemData.clientInfo.marketId, userName: itemData.clientInfo.market });
        }
      });
      const params = {
        saveDraft: !isValidate,
        data
      };
      const validatePromise = [];
      if (this.$refs.clientInfoRef) validatePromise.push(this.$refs.clientInfoRef.validateForm(isValidate));
      for (let i = 0; i < this.pageList.length; i++) {
        const orderInfoRef = this.$refs[`orderInfoRef${i}`] ? this.$refs[`orderInfoRef${i}`][0] : null;
        const resourceInfoRef = this.$refs[`resourceInfoRef${i}`] ? this.$refs[`resourceInfoRef${i}`][0] : null;
        const publishInfoRef = this.$refs[`publishInfoRef${i}`] ? this.$refs[`publishInfoRef${i}`][0] : null;
        if (orderInfoRef) validatePromise.push(orderInfoRef.validateForm(isValidate));
        if (resourceInfoRef) validatePromise.push(resourceInfoRef.validateForm(isValidate));
        if (publishInfoRef) validatePromise.push(publishInfoRef.validateForm(isValidate));
      }

      Promise.all(validatePromise).then(res => {
        // 创建订单时需要确 认框
        this.dialogSummary = params.saveDraft ? '请确认是否创建草稿订单' : '请确认是否创建订单';
        this.dialogTitle = params.saveDraft ? '订单创建草稿确认' : '订单创建确认';
        const dingTalkMsg = params.saveDraft ? '您有新待创建订单需要处理' : '您有新待发布订单需要处理';
        let defaultUser = [];
        if (params.saveDraft) {
          if (clientList.length === 0) {
            ElMessage.warning('请选择销售');
            return;
          }
          defaultUser = clientList;
        } else if (orderOperatorList) {
          defaultUser = orderOperatorList;
        }
        if (defaultUser && defaultUser.length > 0) {
          this.$refs.publishDialogRef.showDialog({ defaultMsg: dingTalkMsg, defaultObjectUser: defaultUser, extendParams: params, receiveDisabled: true });
        } else {
          params.isSendMsg = false;
          this.createOrder(params);
        }
        // this.createOrder(params);
      }).catch((err) => {
        console.log(err);
        ElMessage.warning('请检查信息是否填写完整');
      });
    },
    createOrder(params) {
      const orderStatus = params.saveDraft ? 0 : 1;
      params.url = `${location.origin}?redirect=/orderPage/allOrder?orderStatus=${orderStatus}`;
      this.btnLoading = true;
      createOrderBatch(params).then(res => {
        this.btnLoading = false;
        if (res.code === 501) {
          // 501:销售额度不足
          this.$refs.limitTable.initData(0, res.data);
          return;
        }
        this.$message.success('添加成功');
        this.$router.push({
          name: 'allOrder'
        });
      }, err => {
        this.btnLoading = false;
        if (err.code === 502) {
          // 502:客户额度不足
          this.$refs.limitTable.initData(1, err.data);
          return;
        }
      });
    },

    orderTypeChange(orderType, index) {
      this.$set(this.orderTypeList, index, orderType);
      // this.orderTypeList[index] = orderType;
    },
    getRefData(index) {
      const clientInfoRef = this.$refs.clientInfoRef;
      const orderInfoRef = this.$refs[`orderInfoRef${index}`] ? this.$refs[`orderInfoRef${index}`][0] : null;
      const resourceInfoRef = this.$refs[`resourceInfoRef${index}`] ? this.$refs[`resourceInfoRef${index}`][0] : null;
      const publishInfoRef = this.$refs[`publishInfoRef${index}`] ? this.$refs[`publishInfoRef${index}`][0] : null;
      const discountInfoRef = this.$refs[`discountInfoRef${index}`] ? this.$refs[`discountInfoRef${index}`][0] : null;
      // 客户信息
      const clientSubParams = clientInfoRef ? clientInfoRef.getParams() : {};
      const marketParams = orderInfoRef ? orderInfoRef.getParams().clientInfo : {};
      const clientParams = Object.assign(clientSubParams, marketParams);
      // 订单信息
      const orderInfoRefParams = orderInfoRef ? orderInfoRef.getParams().orderInfo : {};
      const resourceInfoParams = resourceInfoRef ? resourceInfoRef.getParams() : {};
      const publishInfoParams = publishInfoRef ? publishInfoRef.getParams() : {};
      const orderParams = Object.assign(orderInfoRefParams, resourceInfoParams);
      // 成本信息
      const discountInfoParams = discountInfoRef ? JSON.parse(JSON.stringify(discountInfoRef.list)) : {};
      const params = {
        orderInfo: orderParams,
        clientInfo: clientParams,
        costBreakdown: discountInfoParams,
        publishInfo: publishInfoParams
      };
      const relatedIds = this.getRelatedIds(index);
      params.invoiceIds = relatedIds.invoiceIds;
      params.contractIds = relatedIds.contractIds;
      return params;
    },
    // 获取合同和发票
    getRelatedIds(index) {
      const contractSelect = this.$refs[`ContractSelect${index}`] ? this.$refs[`ContractSelect${index}`][0] : null;
      const invoiceSelect = this.$refs[`InvoiceSelect${index}`] ? this.$refs[`InvoiceSelect${index}`][0] : null;
      let contractIds = [];
      let invoiceIds = [];
      if (contractSelect && contractSelect.selectData) {
        contractIds = contractSelect.selectData.map(i => i.id);
      }
      if (invoiceSelect && invoiceSelect.selectData) {
        invoiceIds = invoiceSelect.selectData.map(i => i.id);
      }
      return {
        contractIds: contractIds.join(','),
        invoiceIds: invoiceIds.join(','),
        contract: contractSelect ? contractSelect.selectData : [],
        invoiceInfo: invoiceSelect ? invoiceSelect.selectData : []
      };
    },
    toBack() {
      this.$router.push({
        name: 'allOrder'
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.batch-create-container {
  margin: 16px;
  padding-bottom: 40px;
}
.batch-create-list{
  position: relative;
  margin-top: 12px;
  padding-top: 24px;
  background: #fff;
  & ::v-deep {
    .el-tabs__nav-next, .el-tabs__nav-prev {
      line-height: 31px;
    }
    .el-date-editor.el-input {
      width: 240px;
    }
  }
  & ::v-deep {
    .el-tabs--border-card {
      box-shadow: none;
      border: none;
      &>.el-tabs__content {
        padding: 0;
      }
    }
    // .el-table::before {
    //   border: none;
    //   height: 0;
    // }
    .el-select__tags {
      // overflow: hidden;
      // height: 100%;
      display: flex;
      align-items: center;
      max-width: 100%!important;
    }
    .el-tag.el-tag--info {
      color: #406EFF;
      background-color: #ecf1ff;
    }
    .el-tabs--border-card>.el-tabs__header {
      background: #fff;
      border-bottom: none;
      max-width: calc(100% - 146px);
      margin-left: 146px;
      // padding: 0 32px;
    }
    .el-tabs__item {
      border: 1px solid #DDDDDD;
      margin-right: 16px;
      border-radius: 4px;
      font-size:14px;
      font-weight:400;
      color:rgba(102,102,102,1);
      height: 30px;
      line-height: 30px;
      padding: 0 8px !important;
    }
    .el-tabs--border-card>.el-tabs__header .el-tabs__item.is-active {
      border-color: #E6EDFF;
      background: #FAFBFF;
      &.is-focus {
        box-shadow: none;
      }
    }
    .el-tabs__nav {
      padding: 1px;
    }
    .el-tabs__nav-prev, .el-tabs__nav-next {
      width: 24px;
      &:hover {
        color: #406EFF;
      }
    }
    .el-tabs__nav-next {
      right: -10px;
    }
  }
}
.batch-create-item {
  margin-top: 0px;
}
.batch-create-title {
  display: flex;
  align-items: center;
  margin-top: 24px;
  padding: 0 24px;
  .title {
    color: #666666;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    margin-right: 8px;
    width: 64px;
  }
  .dropdown-title {
    font-size: 14px;
    color: #ddd;
    height: 32px;
    width: 200px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    padding: 0 8px;
    cursor: pointer;
    border: 1px solid #DCDFE6;
  }

  .quote-tip {
    margin-left: 24px;
    color: #999;
    font-size: 14px;
  }
}
.dropdown-item {
  width: 160px;
  font-size: 14px;
}
.add-order-tab {
  padding: 7px 17px;
  position: absolute;
  left: 24px;
  i {
    font-weight: bold;
  }
}
</style>
<style lang="scss">

</style>
